<?php

class FormElement_AjaxCheckboxes extends AbstractAssociationElement
{

  public function beforeIndex()
  {
    if (Simplify::request()->post('action') == 'toggle') {
      $at = $this->getAssocTable();
      $apk = $this->getAssocPrimaryKey();
      $afk = $this->getAssocForeignKey();

      $apid = Simplify::request()->post($apk);
      $afid = Simplify::request()->post($afk);

      $data = array($afk => $afid, $apk => $apid);

      $checked = Simplify::request()->post('checked');

      if ($checked) {
        DB::getInstance()->query("INSERT IGNORE INTO $at " . QueryObject::buildInsert($data))->execute($data);
      }
      else {
        DB::getInstance()->query("DELETE FROM $at WHERE $afk = :$afk AND $apk = :$apk")->execute($data);
      }
    }
  }

  public function render($row, $action)
  {
    switch ($action) {
      case Form::ACTION_VIEW :

        $options = $this->getOptions();
        $values = $this->getValues($row);

        $options = array_intersect_key($options, array_flip($values));

        $html = new HTMLElement('p');
        $html->append("<label>{$this->getTitle()}:</label> ");

        $output = $html->append(implode(', ', $options));

        break;

      default :
        $this->beforeRender($row, $action);

        $view = $this->getView($action);

        $options = $this->getOptions();

        $view->set('route', sy_fix_extension(Simplify::request()->route(), 'json'));
        $view->set('value', $this->getValue($row));
        $view->set('values', $this->getValues($row));
        $view->set('options', $options);
        $view->set('key', $this->assocForeignKey);
        $view->set('rowClass', $this->getRowClass($row));

        $output = $view->render();

        $output = $this->afterRender($output, $row, $action);
    }

    return $output;
  }

}

?>